package en.edu.zxj.rabbit.extensions.demo.listener;

import com.rabbitmq.client.Channel;
import en.edu.zxj.rabbit.extensions.demo.constant.Constants;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-21
 * @time: 12:04:23
 */
// @Component
public class RetryQueueListener {
    @RabbitListener(queues = Constants.RETRY_QUEUE_NAME)
    public void retry(Message message, Channel channel) throws IOException {

        // 模拟处理失败
        try {
            System.out.printf("接收到消息: %s, deliveryTag: %d\n",
                    new String(message.getBody(), "UTF-8"),
                    message.getMessageProperties().getDeliveryTag());
            int num = 1 / 0;
            System.out.println("处理成功");
            // 手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("处理失败");
            // 拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, true);
        }
    }
}
